<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- alert描述 -->
      <el-alert title="添加商品-请填写商品信息" :closable="false" show-icon type="success" center></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex - 0" align-center >
        <el-step  title="基本信息"></el-step>
        <el-step  title="商品参数"></el-step>
        <el-step  title="商品属性"></el-step>
        <el-step  title="商品图片"></el-step>
        <el-step  title="商品内容"></el-step>
        <el-step  title="完成"></el-step>
      </el-steps>
      <!--Form表单 tabs标签页 -->
      <el-form label-position="top" ref="addGoodsInfoFormRef" :model="addGoodsInfoForm" :rules="addGoodsInfoFormRules">
        <el-tabs @tab-click="handleClick" v-model="activeIndex" tab-position="left" :before-leave="tabBeforeLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input  v-model="addGoodsInfoForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addGoodsInfoForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_number">
              <el-input type="number" v-model="addGoodsInfoForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_weight">
              <el-input type="number" v-model="addGoodsInfoForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类"  prop="goods_weight">
              <!-- 级联选中器v-model,保存被选中的值 -->
               <el-cascader
                 v-model="addGoodsInfoForm.goods_cat"
                 :options="goodsCate"
                 :props="props"
                 @change="cascaderChange">
                </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1" >
            <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border  v-for="(valsItem, index) in item.attr_vals" :key="index" :label="valsItem"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- upload -->
            <!-- active图片上传地址 -->
            <!-- on-preview  点击预览时触发-->
            <!-- on-remove 移除图片触发 -->
            <!-- :file-list="fileList"图片上传的列表数组 -->
            <el-upload
              class="upload-demo"
              action="http://liufusong.top:8888/api/private/v1/upload"
              :on-preview="imgPreview"
              :on-remove="imgRemove"
              :headers="uploadHeaders"
              :on-success="uploadSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
              <quill-editor></quill-editor>
              <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
       </el-tabs>
     </el-form>
    </el-card>
    <!-- 点击图片预览对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="imgDialogVisible"
      width="50%"
      >
      <img :src="imgPath" alt="" style="width: 100%">
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      // 步骤条index
      activeIndex: 0,
      // 商品信息表单数据
      addGoodsInfoForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 级联选择器选中的数据 他保存的值与props里的的value关联
        goods_cat: [],
        // ipcs 上传成功后图片在服务器里的地址
        pics: [],
        // attrs 动态参数和静态属性
        attrs: []
      },
      // 添加商品表单的校验规则
      addGoodsInfoFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      },
      // 商品分类数据
      goodsCate: [],
      // 级联选择器配置标识
      props: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      // 动态参数列表
      manyData: [],
      // 静态属性列表
      onlyData: [],
      // 上传图片请求头
      uploadHeaders: {
        authorization: sessionStorage.getItem('token')
      },
      // 预览图片对话框
      imgDialogVisible: false,
      // 图片地址
      imgPath: ''
    }
  },
  created () {
    this.getGoodsCate()
  },
  computed: {
    cateId () {
      if (this.addGoodsInfoForm.goods_cat.length !== 3) return null
      return this.addGoodsInfoForm.goods_cat[2]
    }
  },
  methods: {
    // tabs进入某个子tab时触发的回调
    handleClick () {
      // 判断是否进入了商品参数
      if (this.activeIndex === '1') {
        this.getGoodsParams('many')
      } else if (this.activeIndex === '2') {
        this.getGoodsParams('only')
      }
    },
    // 获取商品参数
    async getGoodsParams (sel) {
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: sel
        }
      })
      if (sel === 'many') {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(',')
        })
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    // 获取级联选择器所需商品种类数据
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      this.goodsCate = res.data
    },
    // 判断用户是否选择了三级
    cascaderChange () {
      if (this.addGoodsInfoForm.goods_cat.length !== 3) {
        this.addGoodsInfoForm.goods_cat = []
      }
    },
    // tabBeforeLeave tabs切换选中焦点时 触发的钩子函数
    tabBeforeLeave (actName, oldName) {
      if (oldName === '0' && this.addGoodsInfoForm.goods_cat.length !== 3) {
        this.$message.error('请选择三级分类')
        return false
      }
    },
    // upload组件预览图片时触发
    imgPreview (file) {
      this.imgDialogVisible = true
      this.imgPath = `http://liufusong.top:8888/${file.response.data.tmp_path}`
    },
    // upload 移除图片时触发
    imgRemove (file) {
      // 当前图片的信息
      const filePath = file.response.data.tmp_path
      const fileIndex = this.addGoodsInfoForm.pics.findIndex(item => {
        return item.pic === filePath
      })
      this.addGoodsInfoForm.pics.splice(fileIndex, 1)
    },
    // 图片上传成功后触发的钩子
    uploadSuccess (res) {
      console.log(res)
      this.addGoodsInfoForm.pics.push({
        pic: res.data.tmp_path
      })
    },
    // 添加商品
    addGoods () {
      // 判断表单 发起请求
      this.$refs.addGoodsInfoFormRef.validate(async flag => {
        if (!flag) return this.$message.error('请完善基本信息')
        // 添加商品时 需要克隆一个表单数据 因为页面组件需要的是数组,而后台需要的是逗号分隔的字符串
        // 如果用户点击确定后表单数据会变成字符串 此时会发生错误
        // 表单数据类型是引用类型,直接赋值的是地址,即需要深拷贝
        // 深拷贝第一种方式 现将拷贝目标对象转化成json字符串 此时这个json对象与目标对象已经没有关系了  再讲json对象转化为对象赋值即可
        // const addGoodsFormData = JSON.parse(JSON.stringify(this.addGoodsInfoForm))
        // 第二种方式lodash closeDeep
        const addGoodsFormData = cloneDeep(this.addGoodsInfoForm)
        addGoodsFormData.goods_cat = addGoodsFormData.goods_cat.join(',')
        // 给请求所需数据添加 静态属性和动态参数
        this.manyData.forEach(item => {
        // 循环manydata 再往表单数据中 push attr_id和 attr_value
          addGoodsFormData.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          })
        })
        this.onlyData.forEach(item => {
        // 循环onlydata 再往表单数据中 push attr_id和 attr_value
          addGoodsFormData.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        console.log(addGoodsFormData)
        const { data: res } = await this.$axios.post('goods', addGoodsFormData)
        if (res.meta.status !== 201) return this.$message.error('创建商品失败')
        this.$message.success('创建商品成功')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped lang="less">
.el-alert {
  margin: 20px;
}
/deep/.el-step__title {
  font-size: 14px;
  font-weight: 200 !important;
}
.el-tabs {
  margin-top: 50px;
}
.el-checkbox{
  width: 300px;
  margin: 10px;
}
/deep/.ql-container{
  height: 400px;
  margin-bottom: 20px;
}
</style>
